# -*- coding: utf-8 -*-
import datetime
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.channel.db import get_channel
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '10196': {
        'API_KEY': 'c5s8cwoqhqzu76ed4cvhw3biam7dw6e1',
    },
    '902': {  # 微信扫码支付
        'gateway': 'http://wx.sachiko.cn/Pay_Index.html',
        'query_gateway': 'http://wx.sachiko.cn/Pay_Trade_query.html',
    },
    '904': {  # 支付宝手机（H5）
        'gateway': 'http://zfbh5.sachiko.cn/Pay_Index.html',
        'query_gateway': 'http://zfbh5.sachiko.cn/Pay_Trade_query.html',
    },
    '926': {  # 银联扫码
        'gateway': 'http://yl.sachiko.cn/Pay_Index.html',
        'query_gateway': 'http://yl.sachiko.cn/Pay_Trade_query.html',
    },
    '929': {  # 原生微信扫码 3.5%
        'gateway': 'http://yswx.sachiko.cn/Pay_Index.html',
        'query_gateway': 'http://yswx.sachiko.cn/Pay_Trade_query.html',
    },
    '930': {  # 原生支付宝扫码 3.5%
        'gateway': 'http://yszfb.sachiko.cn/Pay_Index.html',
        'query_gateway': 'http://yszfb.sachiko.cn/Pay_Trade_query.html',
    },
    '932': {  # 大额银联H5
        'gateway': 'http://deyl.sachiko.cn/Pay_Index.html',
        'query_gateway': 'http://deyl.sachiko.cn/Pay_Trade_query.html',
    },
    '933': {  # PDD支付宝H5
        'gateway': 'http://pddzfbh5.sachiko.cn/Pay_Index.html',
        'query_gateway': 'http://pddzfbh5.sachiko.cn/Pay_Trade_query.html',
    },

}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(service):
    return APP_CONF[service]['gateway']


def _get_query_gateway(service):
    return APP_CONF[service]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    sign = m.hexdigest().upper()
    return sign


def generate_verify_sign(parameter, key):
    s = ''
    for k, v in sorted(parameter.items()):
        s += '%s=%s&' % (k, v)
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    if params.get('attach') or params.get('attach') == '':
        params.pop('attach')
    calculated_sign = generate_verify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xiyangyangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)
    tt = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    parameter_dict = OrderedDict((
        ('pay_memberid', app_id),  # 商户号
        ('pay_orderid', str(pay.id)),  # 订单号
        ('pay_applydate', tt),  # 提交时间
        ('pay_bankcode', service),  # 银行编码
        ('pay_notifyurl', '{}/pay/api/{}/xiyangyangpay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('pay_callbackurl', '{}/pay/api/{}/xiyangyangpay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('pay_amount', '%.2f' % pay_amount),  # 订单金额
    ))
    parameter_dict['pay_md5sign'] = generate_verify_sign(parameter_dict, api_key)
    parameter_dict['pay_productname'] = 'none'  # 商品名称(不参与签名）
    _LOGGER.info("xiyangyangpay create date: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['pay_orderid'])
    html_text = _build_form(parameter_dict, _get_gateway(service))
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info('xiyangyangpay url: %s', url)
    return {'charge_info': url}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("xiyangyangpay notify body: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("xiyangyangpay notify data: %s, order_id is: %s", data, data['orderid'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['orderid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("xiyangyangpay fatal error, pay object not exists, data: %s" % data)
        raise ParamError('xiyangyangpay event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('xiyangyangpay pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('xiyangyangpay pay %s has been processed' % pay_id)
    mch_id = pay.mch_id
    trade_status = str(data['returncode'])
    trade_no = str(pay_id)
    total_fee = float(data['amount'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '00':
        _LOGGER.info('xiyangyangpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    pay = get_pay(pay_id)
    channel = get_channel(pay.channel_id)
    info = json.loads(channel.info)
    parameter_dict = OrderedDict((
        ('pay_memberid', app_id),  # 商户号
        ('pay_orderid', str(pay_id)),  # 订单号
    ))
    parameter_dict['pay_md5sign'] = generate_verify_sign(parameter_dict, api_key)
    _LOGGER.info('xiyangyangpay query data %s, order_id is: %s', json.dumps(parameter_dict),
                 parameter_dict['pay_orderid'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(info['service']), data=parameter_dict, headers=headers, timeout=5)
    data = json.loads(response.text)
    verify_notify_sign(data, api_key)
    _LOGGER.info('xiyangyangpay query response: %s', data)
    if response.status_code == 200:
        status = str(data['returncode'])
        trade_status = data['trade_state']
        total_fee = float(data['amount'])
        trade_no = str(data['orderid'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        if trade_status == 'SUCCESS' and status == '00':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('xiyangyangpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
        else:
            _LOGGER.info(
                'xiyangyangpay query order success,but not pay success, trade_status:%s ' % trade_status)
    else:
        _LOGGER.warn('xiyangyangpay query error, status_code: %s', response.status_code)
